;(function() {
    init_parsley();
    $.fn.modal.Constructor.prototype.enforceFocus = function () { };
    $('#region_id').select2({placeholder: "请选择区域"});
    $("#cabinet_id").select2({placeholder: "请选择柜号"});
    $('#region_id').on('select2:select', function (e) {
        var data = e.params.data;
        var region_id = data.id;
        if (data.id > 0) {
            $.post(
                "/gym/cabinet/getCabinet",
                {"region_id":region_id},
                function(res){
                    close_loading();
                    if(res.flag){
                        $("#cabinet_id").select2('destroy').empty().append("<option value=\"\">请选择柜号</option>");
                        $("#cabinet_id").select2({
                            data:res.data
                        });
                    }else{
                        toastr['error'](res.msg,"操作失败！");
                    }
                }
            );
        }
    });
    $('#cabinet_id').on('select2:select', function (e) {
        var data = e.params.data;
        var price = data.price;
        if (data.id > 0) {
            $("#price").val(price);
            var duration = $("#duration").val();
            if (duration != '') {
                $("#money").val(duration * price);
            }
        }
    });
    $('#employee_id').select2({
        placeholder: "请输入员工姓名/手机号",
        minimumInputLength: 2,
        ajax:{
            delay:1000,
            url:"/gym/cabinet/ajaxSearchEmployee",
            data:function(params){
                var query = {
                    search: params.term,
                    page: params.page || 1
                };
                return query;
            },
            processResults: function (data, params) {
                params.page = params.page || 1;
                return {
                    results: data.results,
                    pagination: {
                        more: data.more
                    }
                };
            },
        }
    });

    $('#order_id').select2({
        placeholder: "请输入会员姓名/手机号/卡号",
        minimumInputLength: 2,
        ajax:{
            delay:1000,
            url:"/gym/cabinet/ajaxSearchMember",
            data:function(params){
                var query = {
                    search: params.term,
                    type: 1,
                    page: params.page || 1
                };
                return query;
            },
            processResults: function (data, params) {
                params.page = params.page || 1;
                return {
                    results: data.results,
                    pagination: {
                        more: data.more
                    }
                };
            },
        }
    });
    $('#order_id').on('select2:select', function (e) {
        var data = e.params.data;
        if (data.id > 0) {
            $('#member_name').val(data.member_name);
            $('#mobile').val(data.mobile);
            $('#gym_card_name').val(data.gym_card_name);
            $('#member_sex').val(data.sex == 1 ? '男' : '女');
            if (!!data.face1) {
                $('#face1').attr('src',data.face1);
            }
        }
    });
$('#confirm_btn').click(function () {
    loading();
    $.post(
        $('#confirm_btn').attr('data-url'),
        {
            order_id :  $('#confirm_btn').attr('data-order-id')
        },
        function(data){
            close_loading();
            if(data.flag){
                $("#tip_modal").modal("hide");
                toastr['success']("操作成功！", '');
                $("#myform #btn-advanced-refresh").trigger("click");// 刷新页面
            }else{
                toastr['error'](data.msg,"操作失败！");
            }
        }
    );
});

    $('#start_date').datepicker({onSelect:gotoDate,format: 'yyyy-mm-dd',todayHighlight:true,clearBtn:true,autoclose:true , language:"zh-CN"}).on('changeDate',gotoDate);
    $('#order_date').datepicker({format: 'yyyy-mm-dd',todayHighlight:true,autoclose:true , language:"zh-CN"});

    $("#form-submit").click(function(){
        var flag=$('#validate-form').parsley('validate' );
        if(flag){
            loading();
            $.post(
                "/gym/cabinet/orderAdd",
                $("#validate-form").serialize(),
                function(data){
                    close_loading();
                    if(data.flag){
                        $("#myModal").modal("hide");
                        toastr['success']("操作成功！", '');
                        $("#myform #btn-advanced-refresh").trigger("click");// 刷新页面
                    }else{
                        toastr['error'](data.msg,"操作失败！");
                    }
                }
            );
        }
    });

    $("#duration").blur(function(){
        var duration = $(this).val();
        var price = $("#price").val();
        var start_date = $('#start_date').val();
        if(!isRealNum(duration)){
            toastr["error"]("请输入正确的数字");
            return;
        }
        if(!isPositiveInteger(duration)) {
            toastr["error"]("租期应为正整数");
            return false;
        }

        if (price != '') {
            $("#money").val(duration * price);
        }

        if (start_date != '') {
            var d = new Date(Date.parse(start_date.replace(/-/g,"/")));
            d.setDate(d.getDate() * 1 + duration * 30);
            $("#end_date").val(d.format("yyyy-MM-dd"));
        }

    });
    function isRealNum(val){
        if(val === "" || val ==null){
            return false;
        }
        if(!isNaN(val)){
            return true;
        }else{
            return false;
        }
    }

    Date.prototype.format = function(fmt) {
        var o = {
            "M+" : this.getMonth()+1,                 //月份
            "d+" : this.getDate(),                    //日
            "h+" : this.getHours(),                   //小时
            "m+" : this.getMinutes(),                 //分
            "s+" : this.getSeconds(),                 //秒
            "q+" : Math.floor((this.getMonth()+3)/3), //季度
            "S"  : this.getMilliseconds()             //毫秒
        };
        if(/(y+)/.test(fmt)) {
            fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
        }
        for(var k in o) {
            if(new RegExp("("+ k +")").test(fmt)){
                fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
            }
        }
        return fmt;
    };
    function gotoDate(){
        var start_date = $("#start_date").val();
        var duration = $("#duration").val();
        if(start_date.length<9){
            toastr["error"]("错误的日期格式");
            return false;
        }
        var d=new Date().format("yyyy-MM-dd");
        if(start_date >= d){
            if (duration != '') {
                var d=new Date(Date.parse(start_date.replace(/-/g,"/")));
                d.setDate(d.getDate() * 1 + duration * 30);
                $("#end_date").val(d.format("yyyy-MM-dd"));
            }
        }else{
            toastr["error"]("开始日期不能小于今日");
            return false;
        }


    }
    function isPositiveInteger(num) {
        var re = /^[1-9]\d*$/ ;
        return re.test(num);
    }
})();